use crate::knowledge_graph::KnowledgeGraph;

/// 推理步骤
#[derive(Debug, Clone)]
pub struct ReasoningStep {
    pub premise: String,
    pub conclusion: String,
    pub confidence: f64,
    pub reasoning_type: ReasoningType,
}

/// 推理类型
#[derive(Debug, Clone)]
pub enum ReasoningType {
    Deductive,   // 演绎推理：从一般到特殊
    Inductive,   // 归纳推理：从特殊到一般
    Abductive,   // 溯因推理：寻找最佳解释
    Analogical,  // 类比推理：通过相似性推理
}

/// 推理链引擎
pub struct ReasoningChain {
    steps: Vec<ReasoningStep>,
    knowledge_graph: KnowledgeGraph,
}

impl ReasoningChain {
    pub fn new(knowledge_graph: KnowledgeGraph) -> Self {
        ReasoningChain {
            steps: Vec::new(),
            knowledge_graph,
        }
    }

    /// 执行推理链
    pub fn reason(&mut self, query: &str) -> ReasoningResult {
        self.steps.clear();
        
        println!("\n🧠 启动推理链...");
        println!("问题: {}", query);

        // 1. 分析问题，识别关键概念
        let keywords = self.extract_keywords(query);
        println!("识别关键词: {:?}", keywords);

        // 2. 检查知识图谱中的相关概念
        let mut known_concepts = Vec::new();
        let mut unknown_concepts = Vec::new();

        for keyword in &keywords {
            if self.knowledge_graph.has_concept(keyword) {
                known_concepts.push(keyword.clone());
            } else {
                unknown_concepts.push(keyword.clone());
            }
        }

        println!("已知概念: {:?}", known_concepts);
        println!("未知概念: {:?}", unknown_concepts);

        // 3. 如果有未知概念，触发好奇心
        if !unknown_concepts.is_empty() {
            return ReasoningResult {
                answer: None,
                confidence: 0.0,
                reasoning_steps: self.steps.clone(),
                requires_learning: true,
                learning_questions: unknown_concepts
                    .iter()
                    .map(|c| format!("我不太了解'{}'，你能教教我吗？", c))
                    .collect(),
            };
        }

        // 4. 基于已知概念进行推理
        if !known_concepts.is_empty() {
            let answer = self.deduce_answer(&known_concepts, query);
            
            ReasoningResult {
                answer: Some(answer),
                confidence: 0.7,
                reasoning_steps: self.steps.clone(),
                requires_learning: false,
                learning_questions: Vec::new(),
            }
        } else {
            ReasoningResult {
                answer: Some("我需要更多信息来回答这个问题。".to_string()),
                confidence: 0.1,
                reasoning_steps: self.steps.clone(),
                requires_learning: true,
                learning_questions: vec!["能告诉我更多背景信息吗？".to_string()],
            }
        }
    }

    /// 提取关键词 - 改进版：智能去除疑问词并匹配已知概念
    fn extract_keywords(&self, text: &str) -> Vec<String> {
        let mut keywords = Vec::new();
        
        // 疑问词和停用词
        let question_words = vec!["什么", "如何", "怎么", "为什么", "哪", "谁", "何时", "哪里", 
                                   "能", "会", "可以", "吗", "呢", "啊"];
        let stop_words = vec!["是", "的", "了", "吗", "呢", "啊", "吧", "一下", "有", "关系"];
        
        // 步骤1：检查是否匹配整个问题作为概念（用于学习问题意图）
        // 例如："你会做什么"可能被学习为一个完整的概念
        let text_lower = text.to_lowercase().trim().to_string();
        if self.knowledge_graph.has_concept(&text_lower) {
            keywords.push(text_lower.clone());
            return keywords;
        }
        
        // 步骤2：尝试从原始文本中匹配已知概念（最长匹配优先）
        let mut matched_concepts: Vec<(String, usize)> = Vec::new();
        for (concept_name, _) in self.knowledge_graph.concepts.iter() {
            if text.contains(concept_name) {
                matched_concepts.push((concept_name.clone(), concept_name.len()));
            }
        }
        
        // 按长度排序，优先使用长的概念
        matched_concepts.sort_by(|a, b| b.1.cmp(&a.1));
        
        // 步骤3：如果找到已知概念，直接使用
        if !matched_concepts.is_empty() {
            for (concept, _) in matched_concepts {
                if !keywords.contains(&concept) {
                    keywords.push(concept);
                }
            }
            return keywords;
        }
        
        // 步骤4：如果没有找到已知概念，进行分词提取
        let mut cleaned_text = text.to_string();
        
        // 去除常见疑问模式
        let patterns = vec![
            ("什么是", ""),
            ("什么叫", ""),
            ("如何", ""),
            ("怎么", ""),
            ("为什么", ""),
            ("解释一下", ""),
            ("告诉我", ""),
            ("能做", ""),
            ("有什么", ""),
            ("和", " "),
            ("与", " "),
            ("？", ""),
        ];
        
        for (pattern, replacement) in patterns {
            cleaned_text = cleaned_text.replace(pattern, replacement);
        }
        
        // 分词
        let words: Vec<String> = cleaned_text
            .split(|c: char| !c.is_alphanumeric() && !c.is_ascii_alphabetic())
            .filter(|w| !w.is_empty() 
                && !stop_words.contains(w) 
                && !question_words.contains(w)
                && w.len() >= 2)  // 过滤单字
            .map(|s| s.to_string())
            .collect();
        
        // 尝试在words中查找概念组合
        for i in 0..words.len() {
            // 尝试2-4个字的组合
            for length in (2..=4).rev() {
                if i + length <= words.len() {
                    let combined = words[i..i+length].join("");
                    if combined.len() >= 4 {
                        keywords.push(combined);
                    }
                }
            }
        }
        
        // 如果仍然没有关键词，返回原始文本作为一个整体关键词
        // 这样可以学习整个问题模式
        if keywords.is_empty() {
            if !text.is_empty() && text.len() >= 2 {
                keywords.push(text_lower);
            } else {
                keywords = words;
            }
        }
        
        // 去重
        keywords.sort();
        keywords.dedup();
        
        keywords
    }

    /// 演绎推理得出答案
    fn deduce_answer(&mut self, concepts: &[String], query: &str) -> String {
        let mut answer_parts = Vec::new();

        for concept in concepts {
            if let Some(concept_info) = self.knowledge_graph.get_concept(concept) {
                // 主要回答：概念的定义
                answer_parts.push(format!(
                    "根据我所学，{}是{}",
                    concept, concept_info.description
                ));

                self.steps.push(ReasoningStep {
                    premise: format!("知识库中的概念: {}", concept),
                    conclusion: concept_info.description.clone(),
                    confidence: concept_info.confidence as f64 / 100.0,
                    reasoning_type: ReasoningType::Deductive,
                });

                // 查找相关概念，但要过滤掉不合适的
                let related = self.knowledge_graph.find_related(concept);
                if !related.is_empty() {
                    // 过滤掉：
                    // 1. 在原始查询中出现的词（避免循环引用）
                    // 2. 疑问词
                    // 3. 太短的词（可能是噪音）
                    // 4. 与当前定义相同的词（避免重复）
                    let current_definition = concept_info.description.clone();
                    
                    let filtered_related: Vec<String> = related
                        .into_iter()
                        .filter(|r| {
                            let r_lower = r.to_lowercase();
                            // 检查是否是查询的一部分
                            let in_query = query.to_lowercase().contains(&r_lower);
                            // 检查是否是疑问词
                            let is_question = r.starts_with("什么") || r.starts_with("为什么") 
                                || r.starts_with("如何") || r.starts_with("怎么");
                            // 检查长度
                            let too_short = r.len() < 2;
                            // 检查是否是当前概念本身
                            let is_self = r_lower == concept.to_lowercase();
                            // 检查是否与当前定义相同（避免重复）
                            let is_same_as_definition = r == &current_definition;
                            // 检查是否太长（可能是整个句子而不是概念名）
                            let too_long = r.len() > 20;
                            
                            !in_query && !is_question && !too_short && !is_self 
                                && !is_same_as_definition && !too_long
                        })
                        .collect();
                    
                    if !filtered_related.is_empty() {
                        // 限制相关概念的数量，避免信息过载
                        let max_related = 3;
                        let related_to_show: Vec<String> = filtered_related
                            .into_iter()
                            .take(max_related)
                            .collect();
                        
                        if !related_to_show.is_empty() {
                            answer_parts.push(format!("它与{}相关", related_to_show.join("、")));
                        }
                    }
                }
            }
        }

        if answer_parts.is_empty() {
            "让我想想...我需要更多线索。".to_string()
        } else {
            // 用句号和空格连接，让输出更清晰
            answer_parts.join("。")
        }
    }

    /// 从对话中学习
    pub fn learn_from_dialogue(&mut self, user_input: &str, _ai_response: &str) {
        println!("\n📚 从对话中学习...");
        
        // 识别定义模式："X是Y"
        // 但要排除疑问句
        if user_input.contains("是") && !self.is_question(user_input) {
            let parts: Vec<&str> = user_input.split("是").collect();
            if parts.len() == 2 {
                let concept = parts[0].trim();
                let definition = parts[1].trim().trim_end_matches(&['。', '？', '吗'][..]);
                
                // 检查concept是否是疑问词
                let question_words = ["什么", "为什么", "如何", "怎么", "哪", "谁"];
                let is_question_word = question_words.iter().any(|&q| concept.contains(q));
                
                if !concept.is_empty() && !definition.is_empty() && !is_question_word {
                    println!("  • 学到新概念: {} = {}", concept, definition);
                    self.knowledge_graph.add_concept(concept, definition, "用户教学");
                }
            }
        }

        // 识别因果关系："X导致Y" 或 "因为X所以Y"
        if user_input.contains("导致") || user_input.contains("所以") {
            println!("  • 学到因果关系");
            // 可以进一步提取并添加到知识图谱
        }

        self.knowledge_graph.record_interaction();
    }
    
    /// 判断是否是问题
    fn is_question(&self, text: &str) -> bool {
        text.ends_with('？') 
            || text.ends_with('吗') 
            || text.ends_with('呢')
            || text.starts_with("什么")
            || text.starts_with("为什么")
            || text.starts_with("如何")
            || text.starts_with("怎么")
            || text.starts_with("哪")
            || text.starts_with("谁")
    }

    /// 获取推理过程的解释
    pub fn explain(&self) -> String {
        if self.steps.is_empty() {
            return "还没有进行推理。".to_string();
        }

        let mut explanation = String::from("推理过程:\n");
        for (i, step) in self.steps.iter().enumerate() {
            explanation.push_str(&format!(
                "  步骤{}: {} → {} (置信度: {:.2})\n",
                i + 1,
                step.premise,
                step.conclusion,
                step.confidence
            ));
        }
        explanation
    }

    /// 获取知识图谱引用
    pub fn knowledge_graph(&self) -> &KnowledgeGraph {
        &self.knowledge_graph
    }

    /// 获取可变知识图谱引用
    pub fn knowledge_graph_mut(&mut self) -> &mut KnowledgeGraph {
        &mut self.knowledge_graph
    }
}

/// 推理结果
#[derive(Debug)]
pub struct ReasoningResult {
    pub answer: Option<String>,
    pub confidence: f64,
    pub reasoning_steps: Vec<ReasoningStep>,
    pub requires_learning: bool,
    pub learning_questions: Vec<String>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_reasoning_chain() {
        let kg = KnowledgeGraph::new();
        let mut rc = ReasoningChain::new(kg);
        
        // 添加概念
        rc.knowledge_graph_mut().add_concept("ai", "人工智能技术", "test");
        
        // 测试推理（注意：分词会把"什么是ai"当作一个整体）
        let result = rc.reason("ai");
        
        // 现在应该能找到答案
        assert!(result.answer.is_some() || result.requires_learning);
    }
}

